<template>
  <van-popup
    v-model:show="popupDisplay"
    position="bottom"
    safe-area-inset-bottom
    teleport="body"
    :close-on-click-overlay="false"
    :close-on-popstate="true"
  >
    <van-date-picker
      v-model="defaultVal"
      :title="title"
      :show-toolbar="true"
      :option-height="48"
      :columns-type="columnsType"
      :max-date="maxDate"
      :min-date="minDate"
      @cancel="handleClose"
      @confirm="handleConfirm"
    />
  </van-popup>
</template>

<script setup lang="ts">
import {
  defineProps, ref, watch, defineEmits,
} from 'vue';
import type { PropType } from 'vue';

import type { DatePickerColumnType } from 'vant';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '选择时间',
  },
  currentValue: {
    type: String,
    default: '',
  },
  columnsType: {
    type: Array as PropType<DatePickerColumnType[]>,
    default: () => ['year', 'month', 'day'],
  },
  minDate: {
    type: Date as PropType<Date>,
    default: () => {
      const today = new Date();
      today.setFullYear(today.getFullYear() - 10);
      return today;
    },
  },
  maxDate: {
    type: Date as PropType<Date>,
    default: () => {
      const today = new Date();
      today.setFullYear(today.getFullYear() + 10);
      return today;
    },
  },
});

const emits = defineEmits([
  'update:visible',
  'change'
]);

// 弹窗打开和关闭
const defaultVal = ref<string[]>([]);
const popupDisplay = ref(false);
watch(
  () => props.visible,
  (newValue) => {
    popupDisplay.value = newValue;
  },
  {
    immediate: true,
  }
);

watch(
  () => props.currentValue,
  (newValue) => {
    if (newValue) {
      const values = newValue.split('-');
      const [year = new Date().getFullYear(), month = '01', day = '01'] = values;
      if (props.columnsType.length === 3) {
        defaultVal.value = [`${year}`, month, day];
      } else if (props.columnsType.length === 2) {
        defaultVal.value = [`${year}`, month];
      } else {
        defaultVal.value = [`${year}`];
      }
    }
  },
  {
    immediate: true,
  }
);

const handleClose = () => {
  popupDisplay.value = false;
  emits('update:visible', false);
};

const handleConfirm = ({ selectedValues }:any) => {
  handleClose();

  const [year = new Date().getFullYear(), month = '01', day = '01'] = selectedValues;
  let curDate = `${year}-${month}-${day}`;
  if (props.columnsType.length === 3) {
    curDate = `${year}-${month}-${day}`;
  } else if (props.columnsType.length === 2) {
    curDate = `${year}-${month}`;
  } else {
    curDate = `${year}`;
  }
  emits('change', curDate);
};
</script>
